package com.iflytek.autofly.setting.biz.system;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.SystemProperties;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.iflytek.autofly.setting.R;
import com.iflytek.autofly.setting.biz.MainActivity;
import com.iflytek.autofly.setting.biz.Notice;
import com.iflytek.autofly.setting.biz.base.BaseFragment;
import com.iflytek.autofly.setting.biz.base.CommonRadioButtonBean;
import com.iflytek.autofly.setting.biz.base.CommonRadioGroupAdpt;
import com.iflytek.autofly.setting.biz.base.SpAdprViewHolder;
import com.iflytek.autofly.setting.biz.base.SpAdpt;
import com.iflytek.autofly.setting.biz.base.SpAdptBean;
import com.iflytek.autofly.setting.biz.receiver.FlySettingReceiver;
import com.iflytek.autofly.setting.util.FlySettings;
import com.iflytek.autofly.setting.widget.InnerListView;
import com.iflytek.autofly.utils.FlyLog;
import com.iflytek.sunflower.FlowerCollector;

import java.util.Calendar;

import static com.iflytek.autofly.radioservice.util.RadioServiceCons.RadioMode;

/**
 * <b>Description: </b>声音设置的fragment<br/>
 * <b>Change History:</b><br/>
 * <table border="1">
 * <tr>
 * <td><b>user</b></td>
 * <td><b>date</b></td>
 * <td><b>time</b></td>
 * <td><b>reason</b></td>
 * </tr>
 * <tr>
 * <td>JunLuan@iflytek.com</td>
 * <td>2015年10月14日</td>
 * <td>上午11:34:14</td>
 * <td>创建此文件</td>
 * </tr>
 * </table>
 *
 * @author JunLuan@iflytek.com
 */
public class SystemFragment extends BaseFragment implements FlyRadioManager.IFlyRadioListener {
    protected static final String TAG = "SystemFragment";
    private static final String[] CMD = {"autotime", "timeformat", "radiomode", "restorefactory", "systemupdate", "about", "sweep", "restart"};
    TimeControl mTimeControl;
    private InnerListView mAboutSysLv;
    private ToggleButton mTimeFormat24Tbn;
    private TextView mAutoTimeDescTv;
    private ToggleButton mAutoTimeTbn;
    private TextView mDataTv;
    private TextView mTimeTv;
    private SystemControl mSysControl;

    private TextView mSysUpValueTv;
    private SysUpView mSysUpView;
    private IntentFilter mIntentFilter;
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case Intent.ACTION_DATE_CHANGED:
                    if (mDataTv != null) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mDataTv.setText(mTimeControl.getDate());
                            }
                        });
                    }
                    break;
                case Intent.ACTION_TIME_CHANGED:
                    if (mTimeTv != null) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTimeTv.setText(mTimeControl.getTime());
                            }
                        });
                    }
                    break;
            }
        }
    };
    private SpAdpt<AboutSystemHolder, CommonRadioButtonBean> aboutSystemAdpt;
    private TextView mRadioModeValueTv;
    private InnerListView mRadioModeList;
    private FlyRadioManager mRadio;
    private RelativeLayout mSweepRl;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        init(view);
        return view;
    }

    @Override
    public void onDestroy() {
        getActivity().unregisterReceiver(mReceiver);

        mSysUpView.fini();
        mSysUpView = null;
        FlyRadioManager.unregisterListener();
        mRadio = null;

        super.onDestroy();
    }

    private void init(final View v) {
        addUnit(R.layout.timesetting, R.layout.timesetting_sub, new OnExpandChangeListener() {
            @Override
            public void onExpandChanged(boolean isExpanded) {
                if (isExpanded) {
                    mAutoTimeDescTv.setVisibility(View.GONE);
                } else {
                    mAutoTimeDescTv.setVisibility(View.VISIBLE);
                }
            }
        }, null);
        addUnit(R.layout.timeformat);
        addUnit(R.layout.radiomode, R.layout.radiomode_sub, new OnExpandChangeListener() {
            @Override
            public void onExpandChanged(boolean isExpanded) {
                if (isExpanded) {
                    mRadioModeValueTv.setVisibility(View.GONE);
                } else {
                    mRadioModeValueTv.setVisibility(View.VISIBLE);
                }
            }
        }, null);
        addUnit(R.layout.restorefactory);
        addUnit(R.layout.systemupdate, R.layout.systemupdate_sub,
                new OnExpandChangeListener() {
                    @Override
                    public void onExpandChanged(boolean isExpanded) {
                        if (isExpanded) {
                            mSysUpValueTv.setVisibility(View.GONE);
                        } else {
                            mSysUpValueTv.setVisibility(View.VISIBLE);
                        }
                    }
                }, null);
        addUnit(R.layout.aboutsystem, R.layout.aboutsystem_sub, new OnExpandChangeListener() {
            @Override
            public void onExpandChanged(boolean isExpanded) {
                if (isExpanded) {
                    FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.system) + "-" + getString(R.string.sys_aboutsystem));
                    initSubViewAboutSystem();
                }
            }
        }, null);
        addUnit(R.layout.systemsweep);
        addUnit(R.layout.reboot);
        addHiddenUnit(R.layout.cellphoneapp, R.layout.cellphoneapp_sub, new OnExpandChangeListener() {
            @Override
            public void onExpandChanged(boolean isExpanded) {
                if (isExpanded) {
                    FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.system) + "-" + getString(R.string.sys_cellphoneapp));
                }
            }
        }, null);
        // FIXME: 2016/1/4
        // temp solution.
        // 点击最后一个item，切换，再点开，箭头状态不对，临时添加一个不可见item解决一下
        addHiddenUnit(R.layout.aboutsystem);

        mRadio = FlyRadioManager.registerListener(getActivity(), this);

        mTimeControl = new TimeControl(getActivity());
        mSysControl = new SystemControl(getActivity());

        mAutoTimeDescTv = (TextView) v.findViewById(R.id.sys_time_desc_tv);
        mAutoTimeTbn = (ToggleButton) v.findViewById(R.id.sys_time_switch_tbn);
        mAutoTimeTbn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.system) + "-" + getString(R.string.sys_time_autoset), "" + isChecked);
                mTimeControl.setAutoTime(isChecked);
                if (isChecked) {
                    collapse(0);
                    setExpandable(0, false);
                } else {
                    setExpandable(0, true);
                    expand(0);
                }
            }
        });
        mAutoTimeTbn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        mDataTv = (TextView) v.findViewById(R.id.sys_time_date_value_tv);
        RelativeLayout dateRl = (RelativeLayout) v.findViewById(R.id.sys_time_date_rl);
        dateRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar calendar = Calendar.getInstance();
                Dialog d;
                d = new FlyDatePickerDialog(getActivity(),
                        new FlyDatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(com.iflytek.autofly.flypicker.DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                mTimeControl.setDate(year, monthOfYear, dayOfMonth);
                                UpdateDateUI();
                            }
                        },
                        calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH),
                        calendar.get(Calendar.DAY_OF_MONTH));
                d.show();
            }
        });
        mTimeTv = (TextView) v.findViewById(R.id.sys_time_time_value_tv);
        RelativeLayout timeRl = (RelativeLayout) v.findViewById(R.id.sys_time_time_rl);
        timeRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                final Calendar calendar = Calendar.getInstance();
                Dialog d;
                d = new FlyTimePickerDialog(getActivity(),
                        new FlyTimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(com.iflytek.autofly.flypicker.TimePicker view, int hourOfDay, int minute) {
                                mTimeControl.setTime(hourOfDay, minute);
                                UpdateTimeUI();

                            }

                        },
                        calendar.get(Calendar.HOUR_OF_DAY),
                        calendar.get(Calendar.MINUTE),
                        mTimeControl.getTimeFormat24());
                d.show();

            }
        });

        RelativeLayout restoreFactoryRl = (RelativeLayout) v.findViewById(R.id.sys_restore_factory_rl);
        restoreFactoryRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.system) + "-" + getString(R.string.sys_restorefactory));

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent("iflytek.intent.action.AUTOFLY_SETTING");
                        intent.putExtra(FlySettingReceiver.DIRECT_CMD, "restoreFactory");
                        Notice.getInstatnce().showWithBroadcast(getString(R.string.sys_restorefactory_warn), false, intent);
                    }
                });
            }
        });

        mTimeFormat24Tbn = (ToggleButton) v.findViewById(R.id.sys_time_format_switch_tbn);
        mTimeFormat24Tbn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.system) + "-" + getString(R.string.sys_time_format), "" + isChecked);
                mTimeControl.setTimeFormat24(isChecked);
                UpdateTimeUI();
            }
        });
        mTimeFormat24Tbn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        RelativeLayout rebootRl = (RelativeLayout) v.findViewById(R.id.sys_reboot_rl);
        rebootRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.system) + "-" + getString(R.string.sys_reboot));
                Intent intent = new Intent("iflytek.intent.action.AUTOFLY_SETTING");
                intent.putExtra(FlySettingReceiver.DIRECT_CMD, "reboot");
                Notice.getInstatnce().showWithBroadcast(getString(R.string.sys_reboot_msg), false, intent);
            }
        });

        mSysUpValueTv = (TextView) v.findViewById(R.id.sys_sysupdate_value_tv);
        initAboutSystemView(v);

        if (mSysUpView == null) {
            mSysUpView = new SysUpView();
        }
        mSysUpView.init(getActivity(), v);

        mSweepRl = (RelativeLayout) v.findViewById(R.id.sys_syssweep_rl);
        final TextView sweepValueTv = (TextView) v.findViewById(R.id.sys_syssweep_value_tv);
        mSweepRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.system) + "-" + getString(R.string.sys_systemsweep));
                mSweepRl.setClickable(false);
                mSysControl.sweep(new SystemControl.ClearProgressCallback() {
                    @Override
                    public void onProgressChanged(final int progress) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                sweepValueTv.setText(String.format(getString(R.string.sys_syssweep_progressing), progress));
                            }
                        });
                    }

                    @Override
                    public void onClearEnd() {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mSweepRl.setClickable(true);
                                sweepValueTv.setText(getString(R.string.sys_syssweep_progress_end));
                            }
                        });

                    }
                });
            }
        });

        mRadioModeValueTv = (TextView) v.findViewById(R.id.sys_radiomode_value_tv);
        mRadioModeList = (InnerListView) v.findViewById(R.id.sys_radiomode_listview);
        CommonRadioGroupAdpt radioModeListAdpt = new CommonRadioGroupAdpt(getActivity());
        radioModeListAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_radio_city), R.string.sys_radio_city));
        radioModeListAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_radio_country), R.string.sys_radio_country));
        mRadioModeList.setAdapter(radioModeListAdpt);
        int index = Settings.Global.getInt(getActivity().getContentResolver(), FlySettings.System.RADIO_MODE, 0);
        mRadioModeList.setItemChecked(index, true);
        mRadioModeValueTv.setText(getString(index == 0 ? R.string.sys_radio_value_city : R.string.sys_radio_value_country));
        mRadioModeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.system) + "-" + getString(R.string.sys_radio), getString((int) id));
                switch ((int) id) {
                    case R.string.sys_radio_city:
                        mRadioModeValueTv.setText(getString(R.string.sys_radio_value_city));
                        if (mRadio != null) {
                            mRadio.setMode(RadioMode.LOCAL_MODE);
                        }
                        Settings.Global.putInt(getActivity().getContentResolver(), FlySettings.System.RADIO_MODE, 0);
                        break;
                    case R.string.sys_radio_country:
                        mRadioModeValueTv.setText(getString(R.string.sys_radio_value_country));
                        if (mRadio != null) {
                            mRadio.setMode(RadioMode.REMOTE_MODE);
                        }
                        Settings.Global.putInt(getActivity().getContentResolver(), FlySettings.System.RADIO_MODE, 1);
                        break;
                    default:
                }
            }
        });
        mRadio.getMode();

        if (mIntentFilter == null) {
            mIntentFilter = new IntentFilter(Intent.ACTION_DATE_CHANGED);
            mIntentFilter.addAction(Intent.ACTION_TIME_CHANGED);
        }
        getActivity().registerReceiver(mReceiver, mIntentFilter);
    }

    public void renew() {
        boolean isAutoTime = mTimeControl.getAutoTime();
        mAutoTimeTbn.setChecked(isAutoTime);
        UpdateDateUI();
        UpdateTimeUI();

        mTimeFormat24Tbn.setChecked(mTimeControl.getTimeFormat24());
    }

    private void UpdateDateUI() {
        mDataTv.setText(mTimeControl.getDate());
    }

    private void UpdateTimeUI() {
        mTimeTv.setText(mTimeControl.getTime());
    }

    @Override
    public void processCommandline(String cmd) {
        switch (cmd) {
            case "sysupopen":
                break;
            case "sweep":
                if (mSweepRl != null) {
                    FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.system) + "-" + getString(R.string.sys_systemsweep), "broadcast");
                    mSweepRl.performClick();
                }
                break;
        }
    }

    @Override
    public String[] getCommands() {
        return CMD;
    }


    private void initAboutSystemView(View v) {
        mAboutSysLv = (InnerListView) v.findViewById(R.id.sys_aboutsystem_listview);
    }

    private void initSubViewAboutSystem() {
        if (AboutSystem.getInstance().isInited()) {
            setSubViewAboutSystem();
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    AboutSystem.getInstance().init(getActivity().getApplicationContext());
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setSubViewAboutSystem();
                        }
                    });
                }
            }).start();
        }
    }

    private void setSubViewAboutSystem() {
        AboutSystem control = AboutSystem.getInstance();
        aboutSystemAdpt = new SpAdpt<AboutSystemHolder, CommonRadioButtonBean>(getActivity().getApplicationContext(), new AboutSystemHolder(), R.layout.sys_aboutsystem_item);

        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_sn), control.getSn(), R.string.sys_aboutsys_sn));
        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_imsi), control.getImsi(), R.string.sys_aboutsys_imsi));
        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_imei), control.getImei(), R.string.sys_aboutsys_imei));
        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_hardwareverison), control.getHardwareVersion(), R.string.sys_aboutsys_hardwareverison));
        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_ubootverison), control.getUbootVersion(), R.string.sys_aboutsys_ubootverison));
        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_mcuverison), control.getMcuVersion(), R.string.sys_aboutsys_mcuverison));
        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_systemverison), control.getSystemVersion(), R.string.sys_aboutsys_systemverison));
        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_softwareverison), control.getSoftwareVersion(), R.string.sys_aboutsys_softwareverison));
        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_basebandverison), SystemProperties.get("gsm.version.baseband", ""), R.string.sys_aboutsys_basebandverison));
        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_bluetooth_addr), "", R.string.sys_aboutsys_bluetooth_addr));
        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_bluetooth_version), SystemProperties.get("persist.sys.bluetooth.version", ""), R.string.sys_aboutsys_bluetooth_version));
        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_mac), control.getMac(), R.string.sys_aboutsys_mac));
        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_ip), control.getIp(), R.string.sys_aboutsys_ip));
        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_navi_map_version), "", R.string.sys_aboutsys_navi_map_version));
        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_navi_app_version), "", R.string.sys_aboutsys_navi_app_version));
        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_service_term), "", R.string.sys_aboutsys_service_term));
        aboutSystemAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_aboutsys_disclaimer), "", R.string.sys_aboutsys_disclaimer));
        mAboutSysLv.setAdapter(aboutSystemAdpt);
        mAboutSysLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch ((int) id) {
                    case R.string.sys_aboutsys_disclaimer:
                        ((MainActivity) getActivity()).showMassiveMessage(
                                getString(R.string.sys_aboutsys_disclaimer_title),
                                getString(R.string.sys_aboutsys_disclaimer_content)
                        );
                        break;
                    case R.string.sys_aboutsys_service_term:
                        ((MainActivity) getActivity()).showMassiveMessage(
                                getString(R.string.sys_aboutsys_service_term_title),
                                getString(R.string.sys_aboutsys_service_term_content)
                        );
                        break;
                    default:
                }
            }
        });

        control.getNaviInfo(new AboutSystem.OnNaviInfoListener() {
            @Override
            public void onNaviInfo(String app, String data) {
                CommonRadioButtonBean appBean = (CommonRadioButtonBean) aboutSystemAdpt.getItemById(R.string.sys_aboutsys_navi_app_version);
                appBean.setDesc(app);
                CommonRadioButtonBean dataBean = (CommonRadioButtonBean) aboutSystemAdpt.getItemById(R.string.sys_aboutsys_navi_map_version);
                dataBean.setDesc(data);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        aboutSystemAdpt.notifyDataSetChanged();
                    }
                });
            }
        });


        control.getBtAddr(new AboutSystem.OnBluetoothInfoListener() {
            @Override
            public void onBluetoothInfo(String btAddr) {
                CommonRadioButtonBean btVerBean = (CommonRadioButtonBean) aboutSystemAdpt.getItemById(R.string.sys_aboutsys_bluetooth_addr);
                btVerBean.setDesc(btAddr);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        aboutSystemAdpt.notifyDataSetChanged();
                    }
                });
            }
        });
    }

    @Override
    public void onModeChanged(final int mode) {
        if (mRadioModeList != null && mRadioModeValueTv != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mRadioModeList != null && mRadioModeValueTv != null) {
                        if (mode == RadioMode.LOCAL_MODE) {
                            mRadioModeList.setItemChecked(0, true);
                            mRadioModeValueTv.setText(getString(R.string.sys_radio_value_city));
                        } else if (mode == RadioMode.REMOTE_MODE) {
                            mRadioModeList.setItemChecked(1, true);
                            mRadioModeValueTv.setText(getString(R.string.sys_radio_value_country));
                        } else {
                            FlyLog.e(TAG, "onModeChanged|invalid mode=" + mode);
                        }
                    }
                }
            });
        }

    }

    class AboutSystemHolder extends SpAdprViewHolder {
        TextView keyTv;
        TextView valueTv;

        @Override
        public void initView(View v) {
            keyTv = (TextView) v.findViewById(R.id.sys_aboutsystem_item_key_tv);
            valueTv = (TextView) v.findViewById(R.id.sys_aboutsystem_item_value_tv);
        }

        @Override
        public void updateView(SpAdptBean b) {
            CommonRadioButtonBean bean = (CommonRadioButtonBean) b;
            keyTv.setText(bean.getText());
            valueTv.setText(bean.getDesc());
        }

        @Override
        public void setStatus(int status) {
        }

        @Override
        public SpAdprViewHolder newInstance() {
            return new AboutSystemHolder();
        }
    }
}
